#This is to obtain:
#Figure_3a.jpg

library("ggplot2")
library("dplyr")
library("lemon")
library("sf")
library("readxl")

#setwd("C:/Users/bogdanp/")
setwd("/Users/bgpopescu/")

#Reading Polygons
x<-st_layers(dsn="./Dropbox/Legacies_Project/Analysis/data/data.gdb")


HRV_adm0 <- st_read(dsn="./Dropbox/Legacies_Project/Analysis/data/data.gdb",
                    layer="HRV_adm0_wgs")

HRV_adm3 <- st_read(dsn="./Dropbox/Legacies_Project/Analysis/data/data.gdb",
                    layer="HRV_adm3")
HRV_adm3<-st_simplify(HRV_adm3, dTolerance = 0.005)
HRV_adm3<-subset(HRV_adm3, select = c(ID_2))
HRV_adm3_data = read_excel("./Dropbox/Legacies_Project/Analysis/data/merge.xlsx", sheet=1, col_names = TRUE, skip = 0)


final_sp<-left_join(HRV_adm3, HRV_adm3_data, by = c("ID_2"="ID_2"))
final_sp<-subset(final_sp, bosnia_border_mun==0)
data<-final_sp
data$dist1 <- as.numeric( with (data,ifelse(data$treat==1, 1, -1)))
data$dist2 <-data$dist1*data$krajna6_distance

data2<-data%>%
  filter(abs(dist2)<70)%>%
  mutate(left=ifelse(dist2<0, "Civilian Territory", "Military Territory"))%>%
  mutate(left_FR=ifelse(dist2<0, "Civile", "Militaire"))
  
###########################
#RD GRAPH: pct_no_water#
###########################

pct_no_water_rd<-ggplot(data=data2, aes(dist2, pct_no_water, color=left, label=NAME_2))+
  geom_smooth(method="lm")+
  geom_point(size=0.5)+
  scale_x_continuous(name="Bandwidth (km)", breaks = seq(-70, 70, 20)) +
  scale_y_continuous(name="Percent")+
  geom_vline(xintercept = 0)+
  theme(plot.title = element_text(hjust = 0.5))+
  geom_text(aes(label = NAME_2),
            size = 2, check_overlap = TRUE, position = position_nudge(y = 1))+
  theme_bw()+
  scale_color_manual("", values=c("Civilian Territory"="black", "Military Territory" = "red"), guide='legend')+
  theme(axis.text.x = element_text(size=14),
        axis.text.y = element_text(size=14),
        axis.title=element_text(size=14),
        plot.title = element_text(hjust = 0.5),
        legend.position = c(1, 0),
        #Legend.position values should be between 0 and 1. c(0,0) corresponds to the "bottom left"
        #and c(1,1) corresponds to the "top right" position.
        legend.box.background = element_rect(fill='white'),
        legend.background = element_blank(),
        legend.text=element_text(size=12))

pct_no_water_rd<-reposition_legend(pct_no_water_rd, 'top right')
pct_no_water_rd

ggsave(pct_no_water_rd, 
       file="./Dropbox/Legacies_Project/Paper/figures/Figure_3a.jpg", 
       height=10, width=20, 
       units = "cm", dpi=300)
